from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.db.models import Max
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404

from questions_management.models import ProjectTopic


# Create your views here.

@login_required(login_url='/login/')
def question_view(request):
    questions = ProjectTopic.objects.all().order_by('-created_at')
    if request.user.role == 'student':
        questions = ProjectTopic.objects.filter(status="approved").order_by('-created_at')
    if request.user.role == 'teacher':
        questions = ProjectTopic.objects.filter(created_by=request.user).order_by('-created_at')


    created_by = request.GET.get('created_by')
    title = request.GET.get('title')
    status = request.GET.get('status')

    # 根据查询参数过滤 questions
    if created_by:
        questions = questions.filter(created_by__username__icontains=created_by)
    if title:
        questions = questions.filter(title__icontains=title)
    if status:
        questions = questions.filter(status=status)
        # 对查询集中的每个对象进行状态映射
    status_mapping = {
        'pending': '待审核',
        'approved': '已通过',
        'rejected': '未通过',
        'draft': '草稿'
    }
    for question in questions:
        question.status = status_mapping.get(question.status, question.status)

    paginator = Paginator(questions, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {
        'questions': page_obj,
        'current_page': page_obj.number,
        'total_pages': paginator.num_pages,
    }
    return render(request, 'admin/question_admin.html', context)


@login_required(login_url='/login/')
def create_question(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        max_students = request.POST.get('max_students')
        status = request.POST.get('status')
        created_by_id = request.POST.get('created_by')
        max_id = ProjectTopic.objects.aggregate(max_id=Max('id'))['max_id'] or 0


        # 创建题目
        question = ProjectTopic.objects.create(
            id=max_id + 1,
            title=title,
            content=content,
            max_students=max_students,
            status=status,
            created_by_id=created_by_id
        )
        return JsonResponse({'success': True, 'message': '创建成功'})
    return JsonResponse({'success': False, 'message': '请求错误'})

@login_required(login_url='/login/')
def update_question(request, question_id):
    try:
        question = ProjectTopic.objects.get(id=question_id)
    except ProjectTopic.DoesNotExist:
        return JsonResponse({'success': False, 'message': '题目不存在'})

    if request.method == 'POST':
        question.title = request.POST.get('title')
        question.content = request.POST.get('content')
        question.max_students = request.POST.get('max_students')
        question.status = request.POST.get('status')
        question.save()
        return JsonResponse({'success': True, 'message': '更新成功'})
    return JsonResponse({'success': False, 'message': '请求错误'})


@login_required(login_url='/login/')
def delete_question(request, question_id):
    # 获取题目对象
    question = get_object_or_404(ProjectTopic, id=question_id)
    if request.method == 'POST':
        if question.current_students > 0:
            return JsonResponse({'success': False, 'message': '题目有学生正在选题，无法删除!'})
        # 检查用户是否是教师且不是题目的创建者，如果是管理员则可以删除
        if request.user.is_authenticated and (request.user.username == question.created_by or request.user.role =='admin'):
            question.delete()  # 允许删除操作继续
        else:
            return JsonResponse({'success': False, 'message': '没有权限删除'})
        return JsonResponse({'success': True, 'message': '删除成功'})
    return JsonResponse({'success': False, 'message': '请求错误'})